package com.boot.util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet
public class FirstEntry extends HttpServlet {
//    @Override
//    //不知道干啥用的233333
//    protected void doPost(HttpServletRequest request, HttpServletResponse response)
//            throws ServletException, IOException {}

    public static boolean isFirstEntry(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        Cookie[] cookies = request.getCookies();//获取本机cookie
        String lastTime=null;
        if (cookies!=null){
            for (Cookie cookie:cookies){
                if ("lastTime".equals(cookie.getName())){
                    lastTime = URLDecoder.decode(cookie.getValue());
//                    out.print("您上次登录的时间为："+lastTime);
//                    break;//获取到key为lasttime的cookie后，跳出循环
                    return false;
                }
            }
        }
        if (lastTime==null){
            out.print("您是第一次访问本网站");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Cookie cookie = new Cookie("lastTime", URLEncoder.encode(sdf.format(new Date())));
        cookie.setMaxAge(1000*60*60*24*10); //保存10天
        response.addCookie(cookie);
        return true;
    }

}
